package com.gxgeek.javabasic.file;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author gaoxing
 * @create 2018-08-27 下午3:09
 */
public class Try {
    public static <T> Consumer<T> cof(UncheckedConsumer<T> mapper) {
        Objects.requireNonNull(mapper);
        return t -> {
            try {
                mapper.accept(t);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        };
    }

    public static <T> Consumer<T> ncof(UncheckedConsumer<T> mapper) {
        Objects.requireNonNull(mapper);
        return t -> {
            try {
                mapper.accept(t);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        };
    }

    public static <T, R> Function<T, R> of(UncheckedFunction<T, R> mapper) {
        Objects.requireNonNull(mapper);
        return t -> {
            try {
                return mapper.apply(t);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        };
    }

    public static <T, R> Function<T, R> eof(UncheckedFunction<T, R> mapper, Exception cex) {
        Objects.requireNonNull(mapper);
        return t -> {
            try {
                return mapper.apply(t);
            } catch (Exception ex) {
                if(cex!=null&&cex.getClass()==ex.getClass()){
                    throw new RuntimeException(cex);
                }else{
                    throw new RuntimeException(ex);
                }
            }
        };
    }

    public static <T, R> Function<T, R> of(UncheckedFunction<T, R> mapper, R defaultR) {
        Objects.requireNonNull(mapper);
        return t -> {
            try {
                return mapper.apply(t);
            } catch (Exception ex) {
                ex.printStackTrace(System.err);
                return defaultR;
            }
        };
    }

    @FunctionalInterface
    public static interface UncheckedFunction<T, R> {
        R apply(T t) throws Exception;
    }

    @FunctionalInterface
    public static interface UncheckedConsumer<T> {
        void accept(T t) throws Exception;
    }

}
